/**
 * 交易对状态监控器
 * 监控币安USDT交易对状态变化，特别关注TRADING -> BREAK的变化
 */

const BinanceStatusService = require('../services/binanceStatusService');
const EmailService = require('../services/emailService');
const storage = require('../utils/storage');
const logger = require('../utils/logger');

class StatusMonitor {
  constructor() {
    this.statusService = new BinanceStatusService();
    this.emailService = new EmailService();
    this.isRunning = false;
    this.checkInterval = null;
    this.intervalMs = parseInt(process.env.STATUS_CHECK_INTERVAL) || 300000; // 默认5分钟
  }

  /**
   * 初始化状态监控器
   */
  async initialize() {
    try {
      logger.info('🔄 初始化交易对状态监控器...');

      // 检查API连接
      const isConnected = await this.statusService.checkConnection();
      if (!isConnected) {
        logger.warn('⚠️  币安API连接失败，但监控器将继续尝试');
      }

      // 初始化邮件服务
      try {
        if (this.emailService && typeof this.emailService.isConfigured === 'function' && this.emailService.isConfigured()) {
          logger.success('✅ 邮件服务已配置');
        } else {
          logger.warn('⚠️  邮件服务未配置，将只记录日志');
        }
      } catch (error) {
        logger.warn('⚠️  邮件服务检查失败，将只记录日志');
      }

      // 执行一次初始检查来建立基线
      logger.info('📊 执行初始状态检查以建立基线...');
      await this.statusService.performStatusCheck();

      logger.success('✅ 交易对状态监控器初始化完成');

    } catch (error) {
      logger.error(`❌ 状态监控器初始化失败: ${error.message}`);
      throw error;
    }
  }

  /**
   * 启动状态监控
   */
  start() {
    if (this.isRunning) {
      logger.warn('⚠️  状态监控器已在运行');
      return;
    }

    logger.info(`🚀 启动交易对状态监控，检查间隔: ${this.intervalMs / 1000} 秒`);
    
    this.isRunning = true;
    
    // 设置定时检查
    this.checkInterval = setInterval(async () => {
      await this.performCheck();
    }, this.intervalMs);

    logger.success('✅ 交易对状态监控已启动');
  }

  /**
   * 停止状态监控
   */
  stop() {
    if (!this.isRunning) {
      logger.warn('⚠️  状态监控器未在运行');
      return;
    }

    logger.info('🛑 停止交易对状态监控...');
    
    this.isRunning = false;
    
    if (this.checkInterval) {
      clearInterval(this.checkInterval);
      this.checkInterval = null;
    }

    logger.success('✅ 交易对状态监控已停止');
  }

  /**
   * 执行一次状态检查
   */
  async performCheck() {
    try {
      logger.debug('🔍 执行定时状态检查...');

      // 执行状态检查
      const result = await this.statusService.performStatusCheck();
      
      // 记录监控活动
      await this.logMonitorActivity(result);

      // 处理告警
      if (result.success && result.alerts.length > 0) {
        await this.handleAlerts(result.alerts);
      }

      return result;

    } catch (error) {
      logger.error(`状态检查执行失败: ${error.message}`);
      
      // 记录错误
      await this.logMonitorActivity({
        success: false,
        message: error.message,
        alerts: [],
        symbolCount: 0,
        duration: 0
      });

      return { success: false, error: error.message };
    }
  }

  /**
   * 处理状态变化告警
   * @param {Array} alerts 告警列表
   */
  async handleAlerts(alerts) {
    try {
      // 分类处理告警
      const criticalAlerts = alerts.filter(alert => alert.changeType === 'CRITICAL');
      const infoAlerts = alerts.filter(alert => alert.changeType === 'INFO');

      logger.info(`📧 处理告警: ${criticalAlerts.length} 个关键告警, ${infoAlerts.length} 个信息告警`);

      // 处理关键告警 (TRADING -> BREAK)
      if (criticalAlerts.length > 0) {
        await this.sendCriticalAlert(criticalAlerts);
      }

      // 处理信息告警
      if (infoAlerts.length > 0) {
        await this.sendInfoAlert(infoAlerts);
      }

      // 记录告警到存储
      await this.saveAlertsToStorage(alerts);

    } catch (error) {
      logger.error(`处理告警失败: ${error.message}`);
    }
  }

  /**
   * 发送关键告警邮件
   * @param {Array} alerts 关键告警列表
   */
  async sendCriticalAlert(alerts) {
    try {
      if (!this.emailService || typeof this.emailService.isConfigured !== 'function' || !this.emailService.isConfigured()) {
        logger.warn('邮件服务未配置，跳过邮件发送');
        return;
      }

      const subject = `🚨 【币安关键告警】${alerts.length} 个交易对状态异常`;
      
      // 生成邮件内容
      const htmlContent = this.generateCriticalAlertHTML(alerts);
      const textContent = this.generateCriticalAlertText(alerts);

      const success = await this.emailService.sendAlert({
        subject: subject,
        html: htmlContent,
        text: textContent,
        priority: 'high'
      });

      if (success) {
        logger.success(`✅ 关键告警邮件发送成功 (${alerts.length} 个告警)`);
      } else {
        logger.error('❌ 关键告警邮件发送失败');
      }

    } catch (error) {
      logger.error(`发送关键告警失败: ${error.message}`);
    }
  }

  /**
   * 发送信息告警邮件
   * @param {Array} alerts 信息告警列表
   */
  async sendInfoAlert(alerts) {
    try {
      if (!this.emailService || typeof this.emailService.isConfigured !== 'function' || !this.emailService.isConfigured()) {
        return;
      }

      // 信息告警可以批量发送，降低邮件频率
      const subject = `ℹ️  【币安状态变化】${alerts.length} 个交易对状态更新`;
      
      const htmlContent = this.generateInfoAlertHTML(alerts);
      const textContent = this.generateInfoAlertText(alerts);

      const success = await this.emailService.sendAlert({
        subject: subject,
        html: htmlContent,
        text: textContent,
        priority: 'normal'
      });

      if (success) {
        logger.info(`📧 状态变化通知发送成功 (${alerts.length} 个变化)`);
      }

    } catch (error) {
      logger.error(`发送信息告警失败: ${error.message}`);
    }
  }

  /**
   * 生成关键告警HTML内容
   */
  generateCriticalAlertHTML(alerts) {
    const timestamp = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
    
    let alertsHTML = '';
    alerts.forEach(alert => {
      alertsHTML += `
        <div style="border-left: 4px solid #dc3545; padding-left: 12px; margin: 8px 0;">
          <h4 style="color: #dc3545; margin: 0;">🚨 ${alert.type} ${alert.symbol}</h4>
          <p style="margin: 4px 0;"><strong>状态变化:</strong> ${alert.previousStatus} → ${alert.currentStatus}</p>
          <p style="margin: 4px 0; font-size: 12px; color: #666;">时间: ${alert.timestamp}</p>
        </div>
      `;
    });

    return `
      <div style="font-family: Arial, sans-serif; max-width: 600px;">
        <h2 style="color: #dc3545;">🚨 币安交易对关键状态告警</h2>
        <p>检测到 <strong>${alerts.length}</strong> 个交易对从 <strong>TRADING</strong> 状态变为 <strong>BREAK</strong> 状态。</p>
        
        <div style="background-color: #f8f9fa; padding: 16px; border-radius: 8px; margin: 16px 0;">
          <h3>📋 详细信息:</h3>
          ${alertsHTML}
        </div>
        
        <div style="background-color: #fff3cd; padding: 12px; border-radius: 6px; margin: 16px 0;">
          <p><strong>⚠️  重要提醒:</strong></p>
          <ul>
            <li>交易对状态从 TRADING 变为 BREAK 表示暂停交易</li>
            <li>请及时检查相关交易策略和持仓</li>
            <li>关注官方公告了解恢复时间</li>
          </ul>
        </div>
        
        <hr style="margin: 20px 0;">
        <p style="font-size: 12px; color: #666;">
          告警时间: ${timestamp}<br>
          监控系统: 多交易所监控系统 v4.2.0
        </p>
      </div>
    `;
  }

  /**
   * 生成关键告警文本内容
   */
  generateCriticalAlertText(alerts) {
    const timestamp = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
    
    let alertsText = '';
    alerts.forEach(alert => {
      alertsText += `\n🚨 ${alert.type} ${alert.symbol}\n`;
      alertsText += `   状态变化: ${alert.previousStatus} → ${alert.currentStatus}\n`;
      alertsText += `   时间: ${alert.timestamp}\n`;
    });

    return `
🚨 币安交易对关键状态告警

检测到 ${alerts.length} 个交易对从 TRADING 状态变为 BREAK 状态。

📋 详细信息:
${alertsText}

⚠️  重要提醒:
- 交易对状态从 TRADING 变为 BREAK 表示暂停交易
- 请及时检查相关交易策略和持仓
- 关注官方公告了解恢复时间

告警时间: ${timestamp}
监控系统: 多交易所监控系统 v4.2.0
    `.trim();
  }

  /**
   * 生成信息告警HTML内容
   */
  generateInfoAlertHTML(alerts) {
    const timestamp = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
    
    let alertsHTML = '';
    alerts.forEach(alert => {
      alertsHTML += `
        <div style="border-left: 4px solid #17a2b8; padding-left: 12px; margin: 8px 0;">
          <h4 style="color: #17a2b8; margin: 0;">ℹ️  ${alert.type} ${alert.symbol}</h4>
          <p style="margin: 4px 0;"><strong>状态变化:</strong> ${alert.previousStatus} → ${alert.currentStatus}</p>
          <p style="margin: 4px 0; font-size: 12px; color: #666;">时间: ${alert.timestamp}</p>
        </div>
      `;
    });

    return `
      <div style="font-family: Arial, sans-serif; max-width: 600px;">
        <h2 style="color: #17a2b8;">ℹ️  币安交易对状态变化通知</h2>
        <p>检测到 <strong>${alerts.length}</strong> 个交易对状态变化。</p>
        
        <div style="background-color: #f8f9fa; padding: 16px; border-radius: 8px; margin: 16px 0;">
          <h3>📋 变化详情:</h3>
          ${alertsHTML}
        </div>
        
        <hr style="margin: 20px 0;">
        <p style="font-size: 12px; color: #666;">
          通知时间: ${timestamp}<br>
          监控系统: 多交易所监控系统 v4.2.0
        </p>
      </div>
    `;
  }

  /**
   * 生成信息告警文本内容
   */
  generateInfoAlertText(alerts) {
    const timestamp = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
    
    let alertsText = '';
    alerts.forEach(alert => {
      alertsText += `\nℹ️  ${alert.type} ${alert.symbol}\n`;
      alertsText += `   状态变化: ${alert.previousStatus} → ${alert.currentStatus}\n`;
      alertsText += `   时间: ${alert.timestamp}\n`;
    });

    return `
ℹ️  币安交易对状态变化通知

检测到 ${alerts.length} 个交易对状态变化。

📋 变化详情:
${alertsText}

通知时间: ${timestamp}
监控系统: 多交易所监控系统 v4.2.0
    `.trim();
  }

  /**
   * 保存告警到存储
   */
  async saveAlertsToStorage(alerts) {
    try {
      const alertData = {
        timestamp: new Date().toISOString(),
        type: 'status_alert',
        exchange: 'binance',
        alertCount: alerts.length,
        criticalAlerts: alerts.filter(alert => alert.changeType === 'CRITICAL').length,
        alerts: alerts
      };

      await storage.logMonitorActivity(alertData);
      logger.debug(`📝 已保存 ${alerts.length} 个告警到存储`);

    } catch (error) {
      logger.error(`保存告警到存储失败: ${error.message}`);
    }
  }

  /**
   * 记录监控活动
   */
  async logMonitorActivity(result) {
    try {
      const activityData = {
        timestamp: new Date().toISOString(),
        type: 'status_monitor',
        exchange: 'binance',
        success: result.success,
        message: result.message || '',
        symbolCount: result.symbolCount || 0,
        alertCount: result.alerts ? result.alerts.length : 0,
        duration: result.duration || 0,
        statusStats: result.statusStats || null
      };

      await storage.logMonitorActivity(activityData);

    } catch (error) {
      logger.error(`记录监控活动失败: ${error.message}`);
    }
  }

  /**
   * 手动触发状态检查（用于测试）
   */
  async triggerCheck() {
    logger.info('🔍 手动触发状态检查...');
    const result = await this.performCheck();
    
    if (result.success) {
      logger.success('✅ 手动状态检查完成');
    } else {
      logger.error('❌ 手动状态检查失败');
    }
    
    return result;
  }

  /**
   * 获取监控器状态
   */
  getStatus() {
    const serviceStatus = this.statusService.getServiceStatus();
    
    return {
      name: 'StatusMonitor',
      description: '币安USDT交易对状态监控器',
      isRunning: this.isRunning,
      checkInterval: `${this.intervalMs / 1000} 秒`,
      emailConfigured: this.emailService && typeof this.emailService.isConfigured === 'function' ? this.emailService.isConfigured() : false,
      service: serviceStatus,
      lastCheck: new Date().toISOString()
    };
  }
}

module.exports = StatusMonitor;
